package com.example.springbatchsample.config;

import com.example.springbatchsample.database.Person;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.item.ItemReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 从数据库中读取
 *
 * @author Yunkai Luo
 * @since 2022/1/28
 **/
@Configuration
public class LancherBatchConfiguration {

    /**
     * 创建任务对象的对象
     */
    @Autowired
    public JobBuilderFactory jobBuilderFactory;

    /**
     * 任务的执行由Step决定,
     * 这个用来创建Step
     */
    @Autowired
    public StepBuilderFactory stepBuilderFactory;

    /**
     * 从数据库中取出用户并处理
     *
     * @param itemReaderDbStepx
     * @return
     */
    @Bean
    public Job handleUserJobx(Step itemReaderDbStepx) {
        return jobBuilderFactory
                .get("handleUserJobx")
                .incrementer(new RunIdIncrementer())
                .flow(itemReaderDbStepx)
                .end()
                .build();
    }

    @Bean
    public Step itemReaderDbStepx(ItemReader<Person> jdbcReader,
            MyItemWriter<Person> myPersonItemWriter,
            LauncherListener launcherListener) {
        return stepBuilderFactory.get("itemReaderDbStepx")
                .<Person, Person>chunk(2)
                .reader(jdbcReader)
                .writer(myPersonItemWriter)
                .listener(launcherListener)
                .build();
    }

}
